package com.soft.mainsite.component.beetl.tag.city;

import cn.hutool.core.convert.Convert;
import com.soft.mainsite.common.exception.CmsException;
import com.soft.mainsite.common.utils.Pojo2MapUtil;
import com.soft.mainsite.module.city.dto.CityDto;
import com.soft.mainsite.module.city.service.CityService;
import org.beetl.core.GeneralVarTagBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * CityListTag.java 此类用于城市列表标签
 *
 * @author:李昭阳
 * @date:2019/5/6 0006
 * @remark:
 */
@Service
@Scope("prototype")
public class CityListTag extends GeneralVarTagBinding {

    @Autowired
    private CityService cityService;

    @Override
    public void render() {
        // 是否关联站点信息 1是0否
        Integer isSite = Convert.toInt(this.getAttributeValue("isSite"));
        try {
            this.wrapRender(isSite);
        } catch (Exception e) {
            throw new CmsException("CityListTag wrapRender异常==" + e.getMessage());

        }

    }

    private void wrapRender(Integer isSite) throws Exception {
        List<CityDto> cityList = new ArrayList<>();
        if (isSite.equals(0)) {
            cityList = cityService.getCityList();
        } else if (isSite.equals(1)) {
            cityList = cityService.getSiteCityList();
        }

        Map<String, List<Map>> resultMap = new TreeMap(
                new Comparator<String>() {
                    @Override
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                }
        );

        for (CityDto cityDto : cityList) {
            if (resultMap.containsKey(cityDto.getCityInitial())) {
                Map cityMap = Pojo2MapUtil.toMap(cityDto);
                resultMap.get(cityDto.getCityInitial()).add(cityMap);
            } else {
                List<Map> tempList = new ArrayList<>();
                Map cityMap = Pojo2MapUtil.toMap(cityDto);
                tempList.add(cityMap);
                resultMap.put(cityDto.getCityInitial(), tempList);
            }
        }

        Set<String> keySet = resultMap.keySet();
        Iterator<String> iter = keySet.iterator();
        int i = 1;
        while (iter.hasNext()) {
            String key = iter.next();
            List<Map> maps = resultMap.get(key);
            Map<String, Object> map = new HashMap<>(16);
            map.put("key", key);
            map.put("list", maps);
            map.put("index", i);
            this.binds(map);
            this.doBodyRender();
            i++;
        }
    }
}
